using System;
using System.IO;
using Microsoft.SPOT;
using System.Net;

namespace TemperatureMicro
{
    class ServerAccess
    {
        public string FlushServer()
        {
            var URI = "http://temperaturerest.cloudapp.net/Measurements/Flush/";
            return HttpRequest(URI, "GET");
        }

        public string GetCurrentTemperature(string id)
        {
            Debug.Print("getting current temperature");
            string uri = "http://temperaturerest.cloudapp.net/Regulator/" + id + "/GetCurrentTemperature/";
            return HttpRequest(uri, "GET");
        }

        public string GetTargetTemperature(string id)
        {
            Debug.Print("getting target temperature");
            string uri = "http://temperaturerest.cloudapp.net/Regulator/" + id + "/GetTargetTemperature/";
            return HttpRequest(uri, "GET");
        }

        public string registerDevice(string deviceType, string macAddress)
        {
            Debug.Print("registrering: " + deviceType);
            string uri = "http://temperaturerest.cloudapp.net/" + deviceType + "/Register/" + macAddress + "/";
            return HttpRequest(uri, "GET");
        }

        public string PostMeasurement(double temperature, int id)
        {
            if (temperature == -258)
            {
                return "OFF";
            }
            else
            {
                string uri = "http://temperaturerest.cloudapp.net/Sensor/" + id + "/Measurement/" + temperature + "/";
                return HttpRequest(uri, "POST");
            }
        }

        private string HttpRequest(string uri, string requestType)                     //sends to the azure server and retrieves the responce string.  
        {
            string responseString;
            using (var restRequest = HttpWebRequest.Create(uri))
            {
                restRequest.Method = requestType;
                restRequest.ContentLength = 0;
                using (var restResponse = restRequest.GetResponse() as HttpWebResponse)
                {
                    using (Stream stream = restResponse.GetResponseStream())
                    {
                        Debug.Print(restResponse.StatusCode.ToString());
                        StreamReader reader = new StreamReader(stream);
                        responseString = reader.ReadToEnd();
                        Debug.Print(responseString);
                    }
                }
            }
            return responseString;
        }
    }
}
